package com.irdstudio.efp.rule.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.ObjectFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.irdstudio.basic.framework.core.util.SpringContextUtils;
import com.irdstudio.efp.rule.common.enumeration.Rule.RuleType;
import com.irdstudio.efp.rule.service.facade.RuleCallService;
import com.irdstudio.efp.rule.service.vo.ReqRuleVo;
import com.irdstudio.efp.rule.service.vo.RespRuleVO;

/**
 * @description:规则调用
 * <b>获取规则结果 add by wangyk3 date:2018/12/29</b>
 * @date:2018年12月24日 下午5:13:39
 * @author:hengyh
 */
@Service("ruleCallService")
public class RuleCallServiceImpl implements RuleCallService {

	private static Logger logger = LoggerFactory.getLogger(RuleCallServiceImpl.class);
	private static ObjectFilter objectFilter = object -> Objects.nonNull(object) && object instanceof RespRuleVO;
	@Override
	public synchronized List<RespRuleVO> executeBatchRule(RuleType rule, ReqRuleVo param) {
		KieSession kieSession = (KieSession) SpringContextUtils.getBean(rule.toString());
		logger.info("业务流水号：" + param.getAppNo() + "规则调用开始，调用规则集id： " + rule.toString() + "  调用参数：" + param.toString());
		List<RespRuleVO> list = null;
		try {
			// 填充对象
			kieSession.insert(param);
			// 执行单条规则 assert kieSession.fireAllRules(filter) == 1
			kieSession.fireAllRules(i -> {
				return true;
			});
			// 获取规则结果
			list = Optional.ofNullable(kieSession.getObjects(objectFilter))
					.orElseGet(ArrayList::new).stream().map(RespRuleVO.class::cast).collect(Collectors.toList());
		} catch (Exception e) {
			logger.info(e.getMessage());
			throw e;
		} finally {
			kieSession.dispose();
			kieSession.destroy();
		}
		logger.info("业务流水号：" + param.getAppNo() + "规则调用结束，返回结果：" + list);
		return list;
	}
}
